package cn.com.cfae.iras.doc.analyze.components.consistency;

import cn.com.cfae.iras.doc.analyze.components.BaseComponent;
import cn.com.cfae.iras.doc.analyze.components.beans.ComponentResult;
import cn.com.cfae.iras.doc.analyze.handUtil.FormatTimeUtil;
import cn.com.cfae.iras.doc.analyze.handUtil.HandingData;
import cn.com.cfae.iras.doc.analyze.parse.kv.KVText;
import cn.com.cfae.iras.doc.analyze.parse.kv.TextLayout;
import cn.com.cfae.iras.doc.analyze.parse.model.ChapterModel;
import cn.com.cfae.iras.doc.analyze.parse.model.DocumentModel;
import cn.com.cfae.iras.doc.analyze.parse.model.ExtractBizModel;
import cn.com.cfae.iras.doc.analyze.parse.model.ExtractItem;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

/**
 * 信息一致性
 * 检查M-3-1和M-3-2中的缴款日期是否一致
 * 预评/发行阶段
 */

@Component("U1002")
@Scope("prototype")
public class U1002 extends BaseComponent {
    private static Logger logger = LoggerFactory.getLogger(U1002.class);
    @Autowired
    private HandingData handingData;
    @Autowired
    private FormatTimeUtil formatTimeUtil;
    @Override
    public List<ComponentResult> handlerM() {
        logger.info("获取U1002组件M");
        List<ComponentResult> componentResults = checkRulesU1002(getCatalogId(),getCatalogId(),getChapterId(),getRuleTitle(),"M-3-1","M-3-2");
        return componentResults;
    }

    @Override
    public List<ComponentResult> handlerBM() {
        logger.info("获取U1002组件BM");
        List<ComponentResult> componentResults = checkRulesU1002(getCatalogId(),getCatalogId(),getChapterId(),getRuleTitle(),"BM-3-1","BM-3-2");
        return componentResults;
    }

    @Override
    public List<ComponentResult> handlerDM() {
        logger.info("获取U1002组件DM");
        List<ComponentResult> componentResults = checkRulesU1002(getCatalogId(),getCatalogId(),getChapterId(),getRuleTitle(),"DM-3-1","DM-3-2");
        return componentResults;
    }

    @Override
    public List<ComponentResult> handlerBDM() {
        logger.info("获取U1002组件BDM");
        List<ComponentResult> componentResults = checkRulesU1002(getCatalogId(),getCatalogId(),getChapterId(),getRuleTitle(),"BDM-3-1","BDM-3-2");
        return componentResults;
    }



    private List<ComponentResult> checkRulesU1002(String model,String catalogId,String chapterId,String ruleName,String table1,String table2){
        DocumentModel extractData = super.getExtractData();
        List<ComponentResult> componentResults = new ArrayList<>();
        ComponentResult componentResult = null;
        ExtractItem extractItem = null;
        int fxrPageNum = 0;
        List<ComponentResult.TextPosition> fxrContentAndPositionList = null;
        int jkjsPageNum = 0;
        List<ComponentResult.TextPosition> jkjsContentAndPositionList = null;
        int startPage = 0;

        String fxrText = null;
        String jkjsText = null;

        boolean isAllErr = false;
        boolean isAllSeem = false;
        try {

            if (extractData!= null){
                ChapterModel chapterModel = extractData.getChapterModel(model);
                startPage = chapterModel!=null?chapterModel.getStartPage():0;

                //发行人 缴款日
                ExtractItem jkrExtractItem = getExtractItem(extractData,model,"FXTK","JKR");
                if (jkrExtractItem!=null){
                    KVText value = jkrExtractItem.getValue();
                    KVText key = jkrExtractItem.getKey();
                    fxrText = value!=null?value.getText():null;
                    List<TextLayout> textLayouts = value != null ? value.getTextLayoutList() : null;
                    fxrPageNum = CollectionUtils.isNotEmpty(textLayouts) ? textLayouts.get(0).getPageNumber() : startPage;
                    fxrContentAndPositionList = key!=null?getContentAndPositionList(key):null;
                }

                if (jkrExtractItem==null){
                    ExtractItem qxrExtractItem  = getExtractItem(extractData,model,"FXTK","QXR");
                    if (qxrExtractItem != null){
                        KVText value = qxrExtractItem.getValue();
                        KVText key = qxrExtractItem.getKey();
                        fxrText = value!=null?value.getText():null;
                        List<TextLayout> textLayouts = value != null ? value.getTextLayoutList() : null;
                        fxrPageNum = CollectionUtils.isNotEmpty(textLayouts) ? textLayouts.get(0).getPageNumber() : startPage;
                        fxrContentAndPositionList = key!=null?getContentAndPositionList(key):null;
                    }
                }
                fxrPageNum = fxrPageNum!=0?fxrPageNum:startPage;


                // 缴款结算 缴款日
                extractItem = getExtractItem(extractData,model,"JKJS","JKR");
                if (extractItem!=null){
                    KVText value = extractItem.getValue();
                    jkjsText = value!=null?value.getText():null;
                    KVText key = extractItem.getKey();
                    List<TextLayout> textLayouts = key != null ? key.getTextLayoutList() : null;
                    jkjsPageNum =  CollectionUtils.isNotEmpty(textLayouts) ? textLayouts.get(0).getPageNumber() : startPage;
                    jkjsContentAndPositionList = key!=null?getContentAndPositionList(key):null;
                }
                jkjsPageNum = jkjsPageNum!=0?jkjsPageNum:startPage;
            }

            if (StringUtils.isNotEmpty(fxrText)){
                componentResult =  handingData.getComponentResult(catalogId,chapterId,ruleName,table1+"章节,缴款日期:"+fxrText,"已抽取",false,getRegulationId(), fxrPageNum,fxrContentAndPositionList,"01");
                componentResults.add(componentResult);
            }else {
                isAllSeem = true;
                componentResult =  handingData.getComponentResult(catalogId,chapterId,ruleName,table1+"章节,缴款日期","未识别,建议人工核对",true,getRegulationId(), fxrPageNum,fxrContentAndPositionList,"03");
                componentResults.add(componentResult);
            }

            if (StringUtils.isNotEmpty(jkjsText)){
                componentResult =  handingData.getComponentResult(catalogId,chapterId,ruleName,table2+"章节,缴款日期:"+jkjsText,"已抽取",false,getRegulationId(), jkjsPageNum,jkjsContentAndPositionList,"01");
                componentResults.add(componentResult);
            }else {
                isAllSeem = true;
                componentResult =  handingData.getComponentResult(catalogId,chapterId,ruleName,table2+"章节,缴款日期","未识别,建议人工核对",true,getRegulationId(), jkjsPageNum,jkjsContentAndPositionList,"03");
                componentResults.add(componentResult);
            }

            if (StringUtils.isNotEmpty(fxrText)&&StringUtils.isNotEmpty(jkjsText)){
                String fxrTimeStr = formatTimeUtil.formatTime(fxrText);
                String jkjsTimeStr= formatTimeUtil.formatTime(jkjsText);
                if (fxrTimeStr.equals(jkjsTimeStr)){
                    componentResult =  handingData.getComponentResult(catalogId,chapterId,ruleName,"缴款日期验证","日期一致",false,getRegulationId(), fxrPageNum,fxrContentAndPositionList,"01");
                    componentResults.add(componentResult);
                }else {
                    isAllErr = true;
                    componentResult =  handingData.getComponentResult(catalogId,chapterId,ruleName,"缴款日期验证","日期不一致,建议人工核对",true,getRegulationId(), fxrPageNum,fxrContentAndPositionList,"02");
                    componentResults.add(componentResult);
                }
            }else {
                isAllSeem = true;
                componentResult =  handingData.getComponentResult(catalogId,chapterId,ruleName,"缴款日期验证","未识别,建议人工核对",true,getRegulationId(), startPage,fxrContentAndPositionList,"03");
                componentResults.add(componentResult);
            }

            if (isAllErr){
                for (ComponentResult result:componentResults){
                    result.setExist("02");
                }
            }
            if (isAllSeem){
                for (ComponentResult result:componentResults){
                    result.setExist("03");
                }
            }
        }catch (Exception e){
            componentResults.clear();
            componentResult =  handingData.getComponentResult(catalogId,chapterId,ruleName,"缴款日期验证","未识别,建议人工核对",true,getRegulationId(), startPage,fxrContentAndPositionList,"03");
            componentResults.add(componentResult);
            logger.error(e.getMessage(),e);
        }
        return  componentResults;
    }



    private ExtractItem getExtractItem(DocumentModel extractData, String chapter, String model, String key){
        ExtractItem extractItem  = null;
        if (extractData!=null){
            ChapterModel chapterModel = extractData.getChapterModel(chapter);
            if (chapterModel != null){
                ExtractBizModel extractMode = chapterModel.getModel(model);
                if (extractMode!=null){
                    extractItem = extractMode.getExtractItem(key);
                }
            }
        }
        return extractItem;
    }

}
